//
//  ImageDownloader.m
//  iPay
//
//  Created by apple on 11-8-3.
//  Copyright 2011 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloader.h"
#import "Cache.h"
#import "CacheManager.h"

@implementation ImageDownloader

@synthesize delegate;
@synthesize activeDownload;
@synthesize imageConnection;
@synthesize imageURL;
@synthesize tag;
@synthesize indexPath;

#define LOG 0

- (void)dealloc{
    
    [activeDownload release];
    
    [imageConnection cancel];
    [imageConnection release];
	[indexPath release];
    
    [super dealloc];
}

- (void)startDownload:(BOOL)cacheable
{
	imageCacheable = cacheable;
	
	//BOOL isCache = [[NSUserDefaults standardUserDefaults] boolForKey: CLEAR_CACHE_SWITCH_STATUS];
	BOOL isCache = YES;
    
	if (!cacheable || !isCache) {
		self.activeDownload = [NSMutableData data];

		NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
								 [NSURLRequest requestWithURL:
								  [NSURL URLWithString:imageURL]] delegate:self];
		self.imageConnection = conn;
		[conn release];
		
		if ([self.delegate respondsToSelector:@selector(openActiovityIndicator:)]) {
			
			[self.delegate openActiovityIndicator: tag];
		}
		if ([self.delegate respondsToSelector:@selector(openActiovityIndicatorCell:)]) {
			
			[self.delegate openActiovityIndicatorCell: indexPath];
		}
		return;
	}
	
	Cache *imgCache = [CacheManager queryCacheWithCacheKey: imageURL];
	
#if LOG
	NSLog(@"startDownload: %@", imgCache.cobject);
#endif
	
	if (imgCache!=nil && imgCache.cobject!=nil && [imgCache.cobject length]>0) {
		
		
		NSData *data = [NSData dataWithContentsOfFile: imgCache.cobject];
		UIImage *image = [UIImage imageWithData: data];
		
		if (image) {
			
			if ([self.delegate respondsToSelector:@selector(appImageDidLoad:withTag:)]) {
				[self.delegate appImageDidLoad: image withTag: tag];
			}
			
			if ([self.delegate respondsToSelector:@selector(appImageDidLoad:withIndexPath:)]) {
				[self.delegate appImageDidLoad: image withIndexPath: indexPath];
			}
		}

	}else {
		self.activeDownload = [NSMutableData data];
		NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:
								 [NSURLRequest requestWithURL:
								  [NSURL URLWithString:imageURL]] delegate:self];
		self.imageConnection = conn;
		[conn release];
		

		if ([self.delegate respondsToSelector:@selector(openActiovityIndicatorCell:)]) {
			[self.delegate openActiovityIndicatorCell: indexPath];
		}
		if ([self.delegate respondsToSelector:@selector(openActiovityIndicator:)]) {
			[self.delegate openActiovityIndicator: tag];
		}
	}

}

- (void)cancelDownload
{
    [self.imageConnection cancel];

    self.imageConnection = nil;
    self.activeDownload = nil;
	self.delegate = nil;
}


#pragma mark -
#pragma mark Download support (NSURLConnectionDelegate)
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[self.activeDownload setLength: 0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.activeDownload appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
	// Clear the activeDownload property to allow later attempts
    self.activeDownload = nil;
    
    // Release the connection now that it's finished
    self.imageConnection = nil;
	
	if ([self.delegate respondsToSelector:@selector(closeActiovityIndicator:)]) {
		
		[self.delegate closeActiovityIndicator: tag];
	}
	
	if ([self.delegate respondsToSelector:@selector(closeActiovityIndicatorCell:)]) {
		
		[self.delegate closeActiovityIndicatorCell: indexPath];
	}
}

- (void)saveImageToDisk:(NSArray *)array{
	
	NSInteger size = [CacheManager queryCacheSize];
	
	if (size > CACHE_WARNING_FOR_MAX_SIZE) {
		[[NSNotificationCenter defaultCenter] 
		 postNotificationName: CACHE_WARNING_FOR_MAX_SIZE_NOTIFICATION 
		 object: nil];
	}
	
	NSData *data = [array objectAtIndex: 0];
	NSString *key = [array objectAtIndex: 1];
	
	NSFileManager *fileManager = [NSFileManager defaultManager];
	
	NSString *cachePath = [NSHomeDirectory() stringByAppendingPathComponent: CACHE_PATH];
	
#if LOG
	NSLog(@"cachePath: %@", cachePath);
#endif
	
	if (![fileManager fileExistsAtPath: cachePath]) {
		
		NSError *error;
		
		BOOL ret = [fileManager createDirectoryAtPath: cachePath
			   withIntermediateDirectories:YES
								attributes:nil
									 error:&error];
		
		if (ret==NO) {
			NSLog(@"%@", [error localizedFailureReason]);
			return;
		}
	}
	
	NSString *imagePath = [cachePath stringByAppendingPathComponent: [key lastPathComponent]];
	
#if LOG
	NSLog(@"imagePath: %@", imagePath);
#endif
	
	int data_len = [data length];
	
	if (data_len <= MAX_CACHE_SIZE_FOR_IMAGE) {
		if([data writeToFile: imagePath atomically: YES]){

			Cache *cache = [[Cache alloc]init];
			cache.ckey = key;
			cache.cobject = imagePath;
			cache.csize = data_len;
			[CacheManager saveCache: cache];
			[cache release];
			
		}
	}

}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{

    UIImage *image = [[UIImage alloc] initWithData:self.activeDownload];

	BOOL isCache = YES;
	if (image && imageCacheable && isCache) {
		
		NSArray *array = [NSArray arrayWithObjects: self.activeDownload, imageURL, nil];		
		[self saveImageToDisk: array];
		
	}
	
	self.activeDownload = nil;
	
	[self.imageConnection cancel];
    self.imageConnection = nil;
	
    if (image) {

        if ([delegate respondsToSelector:@selector(appImageDidLoad:withTag:)]) {
            
            [self.delegate appImageDidLoad: image withTag: tag];
        }

        if ([delegate respondsToSelector:@selector(appImageDidLoad:withIndexPath:)]) {
            [self.delegate appImageDidLoad: image withIndexPath: indexPath];
        }
	
    }else {
        
        UIImage *defaultImage = [UIImage imageNamed:@"icon.png"];
        if ([delegate respondsToSelector:@selector(appImageDidLoad:withTag:)]) {
            
            [self.delegate appImageDidLoad: defaultImage withTag: tag];
        }
        
        if ([delegate respondsToSelector:@selector(appImageDidLoad:withIndexPath:)]) {
            [self.delegate appImageDidLoad: defaultImage withIndexPath: indexPath];
        }
        //NSLog(@"NOIMAGEURL:::%@",imageURL);
    }
    
	[image release];
	
	if ([delegate respondsToSelector:@selector(closeActiovityIndicator:)]) {
		
		[self.delegate closeActiovityIndicator: tag];
	}
	
	if ([delegate respondsToSelector:@selector(closeActiovityIndicatorCell:)]) {
		
		[self.delegate closeActiovityIndicatorCell: indexPath];
	}
	
}

@end
